home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1997 April: Mac OS SDK / Dev.CD Apr 97 SDK1.toast / Development Kits (Disc 1) / Apple Shared Library Manager / ASLM Examples / Sample Apps / CCPlusSample / Sources / Sample.c next >
Encoding:
C/C++ Source or Header  |  1996-11-19  |  27.7 KB  |  816 lines  |  [TEXT/MPS ]

  1. /*
  2.     File:        Sample.c
  3.  
  4.     Contains:    This is a simple application, based on the DTS traffic light example,
  5.                 that demonstrates how to use the Shared Library Manager. It puts the
  6.                 functionality of the traffic light window into a shared library and
  7.                 then uses that library from the client application.
  8.  
  9.     Copyright:    © 1993-1994 by Apple Computer, Inc., all rights reserved.
  10.  
  11. */
  12.  
  13. #include <LibraryManager.h>
  14. #include <LibraryManagerUtilities.h>
  15.  
  16. #include <limits.h>
  17. #include <Types.h>
  18. #include <Resources.h>
  19. #include <QuickDraw.h>
  20. #include <Fonts.h>
  21. #include <Events.h>
  22. #include <Windows.h>
  23. #include <Menus.h>
  24. #include <TextEdit.h>
  25. #include <Dialogs.h>
  26. #include <Desk.h>
  27. #include <ToolUtils.h>
  28. #include <Memory.h>
  29. #include <SegLoad.h>
  30. #include <Files.h>
  31. #include <OSUtils.h>
  32. #include <OSEvents.h>
  33. #include <DiskInit.h>
  34. #include <Packages.h>
  35. #include <Traps.h>
  36.  
  37. #include "Sample.h"
  38. #include "SampleLibrary.h"
  39.  
  40. /* The "g" prefix is used to emphasize that a variable is global. */
  41.  
  42. /* gMac is used to hold the result of a SysEnvirons call. This makes
  43.    it convenient for any routine to check the environment. */
  44.  
  45. SysEnvRec    gMac;                /* set up by Initialize */
  46.  
  47. /* gHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  48.    trap is available. If it is false, we know that we must call GetNextEvent. */
  49.  
  50. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  51.  
  52. /* gInBackground is maintained by our osEvent handling routines. Any part of
  53.    the program can check it to find out if it is currently in the background. */
  54.  
  55. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  56.  
  57. TTrafficLight    *gTrafficLight;    /* instance of the traffic light library */
  58.  
  59. /* Here are declarations for all of the C routines. In MPW 3.0 and later we can use
  60.    actual prototypes for parameter type checking. */
  61.  
  62. void EventLoop( void );
  63. void DoEvent( EventRecord *event );
  64. void AdjustCursor( Point mouse, RgnHandle region );
  65. void GetGlobalMouse( Point *mouse );
  66. void DoUpdate( WindowPtr window );
  67. void DoActivate( WindowPtr window, Boolean becomingActive );
  68. void DoContentClick( WindowPtr window );
  69. void DrawWindow( WindowPtr window );
  70. void AdjustMenus( void );
  71. void DoMenuCommand( long menuResult );
  72. Boolean DoCloseWindow( WindowPtr window );
  73. void Terminate( void );
  74. void UnLoadTrafficLightLibrary();
  75. void LoadTrafficLightLibrary();
  76. void Initialize( void );
  77. void ForceEnvirons( void );
  78. Boolean IsAppWindow( WindowPtr window );
  79. Boolean IsDAWindow( WindowPtr window );
  80. Boolean TrapAvailable( short tNumber, TrapType tType );
  81. void AlertUser( void );
  82.  
  83. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  84.    dependency on the ordering of fields within a Rect */
  85.  
  86. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  87. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  88.  
  89.  
  90. /*————————————————————————————————————————————————————————————————————————————————————
  91.     _DataInit
  92.  
  93.     This routine is part of the MPW runtime library. This external reference to 
  94.     it is done so that we can unload its segment, %A5Init.
  95.  
  96. ————————————————————————————————————————————————————————————————————————————————————*/
  97.  
  98. extern void _DataInit();
  99.  
  100. /*————————————————————————————————————————————————————————————————————————————————————
  101.     main
  102. ————————————————————————————————————————————————————————————————————————————————————*/
  103.  
  104. #pragma segment Main
  105. main()
  106. {
  107.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  108.         
  109.     /*    If you have stack requirements that differ from the default,
  110.         then you could use SetApplLimit to increase StackSpace at 
  111.         this point, before calling MaxApplZone. */
  112.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  113.  
  114.     Initialize();                    /* initialize the program */
  115.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  116.         
  117.     EventLoop();                    /* call the main event loop */
  118. }
  119.  
  120.  
  121. /*————————————————————————————————————————————————————————————————————————————————————
  122.     EventLoop
  123.  
  124.     Get events forever, and handle them by calling DoEvent.
  125.     Get the events by calling WaitNextEvent, if it's available, otherwise
  126.     by calling GetNextEvent. Also call AdjustCursor each time through the loop.
  127.  
  128. ————————————————————————————————————————————————————————————————————————————————————*/
  129.  
  130. #pragma segment Main
  131. void EventLoop()
  132. {
  133.     RgnHandle    cursorRgn;
  134.     Boolean        gotEvent;
  135.     EventRecord    event;
  136.     Point        mouse;
  137.  
  138.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  139.     do {
  140.         /* use WNE if it is available */
  141.         if ( gHasWaitNextEvent ) {
  142.             GetGlobalMouse(&mouse);
  143.             AdjustCursor(mouse, cursorRgn);
  144.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  145.         }
  146.         else {
  147.             SystemTask();
  148.             gotEvent = GetNextEvent(everyEvent, &event);
  149.         }
  150.         if ( gotEvent ) {
  151.             /* make sure we have the right cursor before handling the event */
  152.             AdjustCursor(event.where, cursorRgn);
  153.             DoEvent(&event);
  154.         }
  155.         /*    If you are using modeless dialogs that have editText items,
  156.             you will want to call IsDialogEvent to give the caret a chance
  157.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  158.             for a non-NIL value before calling IsDialogEvent. */
  159.     } while ( true );    /* loop forever; we quit via ExitToShell */
  160. } /*EventLoop*/
  161.  
  162.  
  163. /*————————————————————————————————————————————————————————————————————————————————————
  164.     DoEvent
  165.  
  166.     Do the right thing for an event. Determine what kind of event it is, and call
  167.     the appropriate routines.
  168.  
  169. ————————————————————————————————————————————————————————————————————————————————————*/
  170.  
  171. #pragma segment Main
  172.  
  173. void DoEvent( EventRecord *event)
  174. {
  175.     short        part, err;
  176.     WindowPtr    window;
  177.     Boolean        hit;
  178.     char        key;
  179.     Point        aPoint;
  180.  
  181.     switch ( event->what ) {
  182.         case mouseDown:
  183.             part = FindWindow(event->where, &window);
  184.             switch ( part ) {
  185.                 case inMenuBar:                /* process a mouse menu command (if any) */
  186.                     AdjustMenus();
  187.                     DoMenuCommand(MenuSelect(event->where));
  188.                     break;
  189.                 case inSysWindow:            /* let the system handle the mouseDown */
  190.                     SystemClick(event, window);
  191.                     break;
  192.                 case inContent:
  193.                     if ( window != FrontWindow() ) {
  194.                         SelectWindow(window);
  195.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  196.                     } else
  197.                         DoContentClick(window);
  198.                     break;
  199.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  200.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  201.                     break;
  202.                 case inGrow:
  203.                     break;
  204.                 case inZoomIn:
  205.                 case inZoomOut:
  206.                     hit = TrackBox(window, event->where, part);
  207.                     if ( hit ) {
  208.                         SetPort(window);                /* the window must be the current port... */
  209.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  210.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  211.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  212.                     }
  213.                     break;
  214.             }
  215.             break;
  216.         case keyDown:
  217.         case autoKey:                        /* check for menukey equivalents */
  218.             key = (char)(event->message & charCodeMask);
  219.             if ( event->modifiers & cmdKey )            /* Command key down */
  220.                 if ( event->what == keyDown ) {
  221.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  222.                     DoMenuCommand(MenuKey(key));
  223.                 }
  224.             break;
  225.         case activateEvt:
  226.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  227.             break;
  228.         case updateEvt:
  229.             DoUpdate((WindowPtr) event->message);
  230.             break;
  231.         /*  It is not a bad idea to at least call DIBadMount in response
  232.             to a diskEvt, so that the user can format a floppy. */
  233.         case diskEvt:
  234.             if ( HighWord(event->message) != noErr ) {
  235.                 SetPt(&aPoint, kDILeft, kDITop);
  236.                 err = DIBadMount(aPoint, event->message);
  237.             }
  238.             break;
  239.         case kOSEvent:
  240.         /*    must BitAND with 0x0FF to get only low byte */
  241.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  242.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  243.                     gInBackground = (event->message & kResumeMask) == 0;
  244.                     DoActivate(FrontWindow(), !gInBackground);
  245.                     break;
  246.             }
  247.             break;
  248.     }
  249. } /*DoEvent*/
  250.  
  251.  
  252. /*————————————————————————————————————————————————————————————————————————————————————
  253.     AdjustCursor
  254.  
  255.     Change the cursor's shape, depending on its position. This also calculates the region
  256.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  257.     that region, an event would be generated, causing this routine to be called,
  258.     allowing us to change the region to the region the mouse is currently in. If
  259.     there is more to the event than just “the mouse moved”, we get called before the
  260.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  261.     this is called again before we     fall back into WNE.
  262.  
  263. ————————————————————————————————————————————————————————————————————————————————————*/
  264.  
  265. #pragma segment Main
  266. void AdjustCursor( Point mouse, RgnHandle region )
  267. {
  268.     WindowPtr    window;
  269.     RgnHandle    arrowRgn;
  270.     RgnHandle    plusRgn;
  271.     Rect        globalPortRect;
  272.  
  273.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  274.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  275.         /* calculate regions for different cursor shapes */
  276.         arrowRgn = NewRgn();
  277.         plusRgn = NewRgn();
  278.  
  279.         /* start with a big, big rectangular region */
  280.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  281.  
  282.         /* calculate plusRgn */
  283.         if ( IsAppWindow(window) ) {
  284.             SetPort(window);    /* make a global version of the viewRect */
  285.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  286.             globalPortRect = window->portRect;
  287.             RectRgn(plusRgn, &globalPortRect);
  288.             SectRgn(plusRgn, window->visRgn, plusRgn);
  289.             SetOrigin(0, 0);
  290.         }
  291.  
  292.         /* subtract other regions from arrowRgn */
  293.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  294.  
  295.         /* change the cursor and the region parameter */
  296.         if ( PtInRgn(mouse, plusRgn) ) {
  297.             SetCursor(*GetCursor(plusCursor));
  298.             CopyRgn(plusRgn, region);
  299.         } else {
  300.             SetCursor(&qd.arrow);
  301.             CopyRgn(arrowRgn, region);
  302.         }
  303.  
  304.         /* get rid of our local regions */
  305.         DisposeRgn(arrowRgn);
  306.         DisposeRgn(plusRgn);
  307.     }
  308. } /*AdjustCursor*/
  309.  
  310. /*————————————————————————————————————————————————————————————————————————————————————
  311.     GetGlobalMouse
  312.  
  313.     Get the global coordinates of the mouse. When you call OSEventAvail
  314.     it will return either a pending event or a null event. In either case,
  315.     the where field of the event record will contain the current position
  316.     of the mouse in global coordinates and the modifiers field will reflect
  317.     the current state of the modifiers. Another way to get the global
  318.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  319.     being sure that thePort is set to a valid port.
  320.  
  321. ————————————————————————————————————————————————————————————————————————————————————*/
  322.  
  323. #pragma segment Main
  324. void GetGlobalMouse(Point    *mouse)
  325. {
  326.     EventRecord    event;
  327.     
  328.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  329.     *mouse = event.where;                /* just the mouse position */
  330. } /*GetGlobalMouse*/
  331.  
  332.  
  333. /*————————————————————————————————————————————————————————————————————————————————————
  334.     DoUpdate
  335.         
  336.     This is called when an update event is received for a window.
  337.     It calls DrawWindow to draw the contents of an application window.
  338.     As an effeciency measure that does not have to be followed, it
  339.     calls the drawing routine only if the visRgn is non-empty. This
  340.     will handle situations where calculations for drawing or drawing
  341.     itself is very time-consuming.
  342.  
  343. ————————————————————————————————————————————————————————————————————————————————————*/
  344.  
  345. #pragma segment Main
  346. void DoUpdate( WindowPtr window)
  347. {
  348.     if ( IsAppWindow(window) ) {
  349.         BeginUpdate(window);                /* this sets up the visRgn */
  350.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  351.             DrawWindow(window);
  352.         EndUpdate(window);
  353.     }
  354. } /*DoUpdate*/
  355.  
  356. /*————————————————————————————————————————————————————————————————————————————————————
  357.     DoActivate
  358.     
  359.     This is called when a window is activated or deactivated.
  360.     In Sample, the Window Manager's handling of activate and
  361.     deactivate events is sufficient. Other applications may have
  362.     TextEdit records, controls, lists, etc., to activate/deactivate. 
  363.  
  364. ————————————————————————————————————————————————————————————————————————————————————*/
  365.  
  366. #pragma segment Main
  367. void DoActivate(WindowPtr window, Boolean becomingActive)
  368. {
  369.     if ( IsAppWindow(window) ) {
  370.         if ( becomingActive )
  371.             /* do whatever you need to at activation */ ;
  372.         else
  373.             /* do whatever you need to at deactivation */ ;
  374.     }
  375. } /*DoActivate*/
  376.  
  377.  
  378. /*————————————————————————————————————————————————————————————————————————————————————
  379.     DoContentClick
  380.  
  381.     This is called when a mouse-down event occurs in the content of a window.
  382.     Other applications might want to call FindControl, TEClick, etc., to
  383.     further process the click.
  384.  
  385. ————————————————————————————————————————————————————————————————————————————————————*/
  386.  
  387. #pragma segment Main
  388.  
  389. void DoContentClick ( WindowPtr window )
  390.     #pragma unused( window )
  391.     
  392.     /* Here we are going to toggle the traffic light by getting the previous state 
  393.        and inverting it to new state. All the calls are going through v-table */
  394.       
  395.     SetLightState( gTrafficLight, !GetLightState(gTrafficLight) );
  396.     
  397. } /*DoContentClick*/
  398.  
  399.  
  400. /*————————————————————————————————————————————————————————————————————————————————————
  401.     DrawWindow
  402.  
  403.     Draw the contents of the application window. We do some drawing in color, using
  404.       Classic QuickDraw's color capabilities. This will be black and white on old
  405.        machines, but color on color machines. At this point, the window’s visRgn
  406.        is set to allow drawing only where it needs to be done.
  407.  
  408. ————————————————————————————————————————————————————————————————————————————————————*/
  409.  
  410. #pragma segment Main
  411.  
  412. void DrawWindow(WindowPtr window)
  413.     #pragma unused( window )
  414.     
  415.     /* DrawLight draws the traffic light through FunctionSets */
  416.     
  417.     DrawLight(gTrafficLight);
  418.  
  419. } /*DrawWindow*/
  420.  
  421.  
  422. /*————————————————————————————————————————————————————————————————————————————————————
  423.     AdjustMenus
  424.     
  425.     Enable and disable menus based on the current state.
  426.     The user can only select enabled menu items. We set up all the menu items
  427.     before calling MenuSelect or MenuKey, since these are the only times that
  428.     a menu item can be selected. Note that MenuSelect is also the only time
  429.     the user will see menu items. This approach to deciding what enable/
  430.     disable state a menu item has the advantage of concentrating all
  431.     the decision-making in one routine, as opposed to being spread throughout
  432.     the application. Other application designs may take a different approach
  433.     that is just as valid.
  434.  
  435. ————————————————————————————————————————————————————————————————————————————————————*/
  436.  
  437. #pragma segment Main
  438. void AdjustMenus()
  439. {
  440.     MenuHandle    menu;
  441.  
  442.     WindowPtr window = FrontWindow();
  443.  
  444.     menu = GetMenuHandle(mFile);
  445.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  446.         EnableItem(menu, iClose);
  447.     else
  448.         DisableItem(menu, iClose);    /* but not our traffic light window */
  449.  
  450.     menu = GetMenuHandle(mEdit);
  451.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  452.         EnableItem(menu, iUndo);
  453.         EnableItem(menu, iCut);
  454.         EnableItem(menu, iCopy);
  455.         EnableItem(menu, iClear);
  456.         EnableItem(menu, iPaste);
  457.     } else {                        /* …but we don’t use it */
  458.         DisableItem(menu, iUndo);
  459.         DisableItem(menu, iCut);
  460.         DisableItem(menu, iCopy);
  461.         DisableItem(menu, iClear);
  462.         DisableItem(menu, iPaste);
  463.     }
  464.     
  465.     /* after adjusting the application's menus adjust the traffic light menus by
  466.        going using the FunctionSets */
  467.      
  468.     AdjustTrafficLightMenus( gTrafficLight, IsAppWindow(window) );
  469.  
  470. } /*AdjustMenus*/
  471.  
  472. /*————————————————————————————————————————————————————————————————————————————————————
  473.     DoMenuCommand
  474.     
  475.     This is called when an item is chosen from the menu bar (after calling
  476.     MenuSelect or MenuKey). It performs the right operation for each command.
  477.     It is good to have both the result of MenuSelect and MenuKey go to
  478.     one routine like this to keep everything organized. It checks to see if the 
  479.     menu hit where the Apple, File, or Edit if so it calls the local DoMenuCommand
  480.     else it must be our traffic light's menu, therefore traffic light menu command 
  481.     is being called.
  482.  
  483. ————————————————————————————————————————————————————————————————————————————————————*/
  484.  
  485. #pragma segment Main
  486. void DoMenuCommand(long menuResult)
  487. {
  488.     short        menuID;                /* the resource ID of the selected menu */
  489.     short        menuItem;            /* the item number of the selected menu */
  490.     short        itemHit;
  491.     Str255        daName;
  492.     short        daRefNum;
  493.     Boolean        handledByDA;
  494.  
  495.     /* Here we are going to get a pointer to our object TLibraryFile this is 
  496.        necessary for allocating our traffic light's resources */
  497.     
  498.     menuID = HighWord(menuResult);    /* use macros for efficiency to... */
  499.     menuItem = LowWord(menuResult);    /* get menu item number and menu number */
  500.  
  501.     switch ( menuID ) {
  502.         case mApple:
  503.             switch ( menuItem ) {
  504.                 case iAbout:        /* bring up alert for About */
  505.                     itemHit = Alert(rAboutAlert, nil);
  506.                     break;
  507.                 default:            /* all non-About items in this menu are DAs */
  508.                     /* type Str255 is an array in MPW 3 */
  509.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  510.                     daRefNum = OpenDeskAcc(daName);
  511.                     break;
  512.             }
  513.             break;
  514.         case mFile:
  515.             switch ( menuItem ) {
  516.                 case iClose:
  517.                     DoCloseWindow(FrontWindow());
  518.                     break;
  519.                 case iQuit:
  520.                     Terminate();
  521.                     break;
  522.             }
  523.             break;
  524.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  525.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing  */
  526.             break;
  527.         case mLight:                /* this must be our shared library resource */
  528.             /* pass the instance to the our traffic light */
  529.             DoTrafficLightMenuCommand( gTrafficLight, menuItem ); /* Do traffic light's menu command */
  530.             break;
  531.     }
  532.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  533. } /*DoMenuCommand*/
  534.  
  535. /*————————————————————————————————————————————————————————————————————————————————————
  536.     DoCloseWindow
  537.     
  538.     Close a window. This handles desk accessory and application windows. Note the
  539.     traffic library manager allocated the windowrecord for window, so disposing of
  540.     the WindowRecord should be left upon the traffic light library.
  541.     
  542. ————————————————————————————————————————————————————————————————————————————————————*/
  543.  
  544.  
  545. #pragma segment Main
  546. Boolean DoCloseWindow(WindowPtr window)
  547. {
  548.     if ( IsDAWindow(window) )
  549.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  550.     else if ( IsAppWindow(window) )
  551.         FreeTrafficLight( gTrafficLight );/*  done with trafficlight, deallocate */
  552.         
  553.     return true;
  554. } /*DoCloseWindow*/
  555.  
  556. /*————————————————————————————————————————————————————————————————————————————————————
  557.     Terminate
  558.  
  559.     Cleanup the application and exits. Close all of the windows, and cleanup our 
  560.     library. We replace the ExitToShell by UnLoadTrafficLightLibrary so we get a 
  561.     chance to unload the library and cleanup the library manager.
  562.   
  563. ————————————————————————————————————————————————————————————————————————————————————*/
  564.  
  565. #pragma segment Main
  566. void Terminate()
  567. {
  568.     WindowPtr    aWindow;
  569.     Boolean        closed;
  570.     
  571.     closed = true;
  572.     do {
  573.         aWindow = FrontWindow();                /* get the current front window */
  574.         if (aWindow != nil)
  575.             closed = DoCloseWindow(aWindow);    /* close this window */    
  576.     }
  577.     while (closed && (aWindow != nil));
  578.     if (closed)
  579.         UnLoadTrafficLightLibrary();        /* exit if no cancellation */
  580. } /*Terminate*/
  581.  
  582.  
  583. /*————————————————————————————————————————————————————————————————————————————————————
  584.     UnLoadTrafficLightLibrary
  585.     
  586.     unload the traffic light object and free the memory allocated by our library
  587.  
  588. ————————————————————————————————————————————————————————————————————————————————————*/
  589.  
  590. void UnLoadTrafficLightLibrary()
  591. {
  592.     /* A library loaded with LoadFunctionSet() is not
  593.         unloaded until all objects from the library
  594.         are deleted and an UnloadFunctionSet() call is 
  595.         made to balance each LoadFunctionSet() call */
  596.     UnloadFunctionSet(kTrafficLightFunctionSet);
  597.  
  598.     CleanupLibraryManager();                /* clean up the library manager we are done. */
  599.     ExitToShell();                            /* Hasta la Vista baby! */
  600. } /* UnLoadTrafficLightLibrary */
  601.  
  602. /*————————————————————————————————————————————————————————————————————————————————————
  603.     LoadTrafficLightLibrary
  604.     
  605.     load the traffic light library. This library automatically creates a window and
  606.     attach a traffic menu to our current menu.
  607.  
  608. ————————————————————————————————————————————————————————————————————————————————————*/
  609.  
  610. void LoadTrafficLightLibrary()
  611. {
  612.     
  613.     /* always initilize the library manager before any Shared Library calls. This
  614.        creates a local instance of TLibraryManager for accessing our libraries. */
  615.  
  616.     if( InitLibraryManager( 0,                /* we don't need memory in our local pool */
  617.                             kCurrentZone,     /* use application zone = current zone */
  618.                             kNormalMemory    /* default memory type, no VM stuff */
  619.                           ) == kNoError ) {
  620.  
  621.         /* make sure the library is available before initializing trafficlight(via LoadFunctionSet) */
  622.         if( LoadFunctionSet(kTrafficLightFunctionSet, true )  == kNoError)
  623.         {
  624.             if( !(gTrafficLight = NewTrafficLight()) )         /* create an instance of TTrafficLight */
  625.                 AlertUser();
  626.         }
  627.         else
  628.             AlertUser();
  629.     }
  630.     else
  631.         AlertUser();                        /* not good. SLM IS NOT INSLALLED */
  632.  
  633. } /* LoadTrafficLightLibrary */
  634.  
  635. /*————————————————————————————————————————————————————————————————————————————————————
  636.     Initialize
  637.     
  638.     Set up the whole world, including global variables, Toolbox managers,
  639.     and menus. Sample is going to create its window, and traffic menu through its
  640.     traffic library, using the shared library manager(Nahhhh...). The Library auto-
  641.     matically create a window, attach a menu and draws the traffic light.
  642.  
  643. ————————————————————————————————————————————————————————————————————————————————————*/
  644.  
  645. #pragma segment Initialize
  646. void Initialize()
  647. {
  648.     Handle        menuBar;
  649.     long        total, contig;
  650.     EventRecord event;
  651.     short        count;
  652.  
  653.     gInBackground = false;
  654.  
  655.     InitGraf((Ptr) &qd.thePort);
  656.     InitFonts();
  657.     InitWindows();
  658.     InitMenus();
  659.     TEInit();
  660.     InitDialogs(nil);
  661.     InitCursor();
  662.          
  663.     /* This next bit of code is necessary to allow the default button of our
  664.        alert be outlined */
  665.  
  666.     for (count = 1; count <= 3; count++)
  667.         EventAvail(everyEvent, &event);
  668.          
  669.     /* Ignore the error returned from SysEnvirons; even if an error occurred,
  670.        the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  671.        call to SysEnvirons by calling it after initializing AppleTalk.*/
  672.  
  673.     SysEnvirons(kSysEnvironsVersion, &gMac);
  674.     
  675.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  676.     
  677.     if (gMac.machineType < 0) AlertUser();
  678.             
  679.     /* Move TrapAvailable call to after SysEnvirons so that we can tell
  680.        in TrapAvailable if a tool trap value is out of range. */
  681.  
  682.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  683.           
  684.     /* We used to make a check for memory at this point by examining ApplLimit,
  685.        ApplicationZone, and StackSpace and comparing that to the minimum size we told
  686.        MultiFinder we needed. This did not work well because it assumed too much about
  687.        the relationship between what we asked MultiFinder for and what we would actually
  688.        get back, as well as how to measure it. Instead, we will use an alternate
  689.        method comprised of two steps. */
  690.  
  691.     /* It is better to first check the size of the application heap against a value
  692.        that you have determined is the smallest heap the application can reasonably
  693.        work in. This number should be derived by examining the size of the heap that
  694.        is actually provided by MultiFinder when the minimum size requested is used.
  695.        The derivation of the minimum size requested from MultiFinder is described
  696.        in Sample.h. The check should be made because the preferred size can end up
  697.        being set smaller than the minimum size by the user. This extra check acts to
  698.        insure that your application is starting from a solid memory foundation. */
  699.  
  700.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  701.  
  702.     /* Next, make sure that enough memory is free for your application to run. It
  703.        is possible for a situation to arise where the heap may have been of required
  704.        size, but a large scrap was loaded which left too little memory. To check for
  705.        this, call PurgeSpace and compare the result with a value that you have determined
  706.        is the minimum amount of free memory your application needs at initialization.
  707.        This number can be derived several different ways. One way that is fairly
  708.        straightforward is to run the application in the minimum size configuration
  709.        as described previously. Call PurgeSpace at initialization and examine the value
  710.        returned. However, you should make sure that this result is not being modified
  711.        by the scrap's presence. You can do that by calling ZeroScrap before calling
  712.        PurgeSpace. Make sure to remove that call before shipping, though.*/
  713.         
  714.     PurgeSpace(&total, &contig);
  715.     if (total < kMinSpace) AlertUser();
  716.  
  717.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  718.     if ( menuBar == nil ) AlertUser();
  719.     SetMenuBar(menuBar);                    /* install menus */
  720.     DisposeHandle(menuBar);
  721.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  722.  
  723.     DrawMenuBar();                            /* go ahead and update the menu bar */
  724.  
  725.     LoadTrafficLightLibrary();                /* Load trafficlight shared library */
  726.     
  727. } /*Initialize*/
  728.  
  729. /*————————————————————————————————————————————————————————————————————————————————————
  730.     IsAppWindow
  731.     
  732.     Check to see if a window belongs to the application. If the window pointer
  733.     passed was NIL, then it could not be an application window. WindowKinds
  734.     that are negative belong to the system and windowKinds less than userKind
  735.     are reserved by Apple except for windowKinds equal to dialogKind, which
  736.     mean it is a dialog.
  737.  
  738. ————————————————————————————————————————————————————————————————————————————————————*/
  739.  
  740. #pragma segment Main
  741. Boolean IsAppWindow( WindowPtr window)
  742. {
  743.     short        windowKind;
  744.  
  745.     if ( window == nil )
  746.         return false;
  747.     else {    /* application windows have windowKinds = userKind (8) */
  748.         windowKind = ((WindowPeek) window)->windowKind;
  749.         return ( windowKind == userKind );
  750.     }
  751. } /*IsAppWindow*/
  752.  
  753. /*————————————————————————————————————————————————————————————————————————————————————
  754.     IsDAWindow
  755.  
  756.     Check to see if a window belongs to a desk accessory
  757.  
  758. ————————————————————————————————————————————————————————————————————————————————————*/
  759.  
  760. #pragma segment Main
  761. Boolean IsDAWindow(WindowPtr window)
  762. {
  763.     if ( window == nil )
  764.         return false;
  765.     else    /* DA windows have negative windowKinds */
  766.         return ( ((WindowPeek) window)->windowKind < 0 );
  767. } /*IsDAWindow*/
  768.  
  769.  
  770. /*————————————————————————————————————————————————————————————————————————————————————
  771.     TrapAvailable
  772.  
  773.     Check to see if a given trap is implemented. This is only used by the
  774.     Initialize routine in this program, so we put it in the Initialize segment.
  775.     The recommended approach to see if a trap is implemented is to see if
  776.     the address of the trap routine is the same as the address of the
  777.     Unimplemented trap.
  778.  
  779. ————————————————————————————————————————————————————————————————————————————————————*/
  780.  
  781. #pragma segment Initialize
  782. Boolean TrapAvailable( short tNumber, TrapType tType)
  783. {
  784.     if ( ( tType == ToolTrap ) &&
  785.         ( gMac.machineType > envMachUnknown ) &&
  786.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  787.         tNumber = tNumber & 0x03FF;
  788.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  789.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  790.     }
  791.     return NGetTrapAddress(tNumber, tType) != NGetTrapAddress(_Unimplemented, tType);
  792. } /*TrapAvailable*/
  793.  
  794. /*————————————————————————————————————————————————————————————————————————————————————
  795.     AlertUser
  796.     
  797.     Display an alert that tells the user an error occurred, then exit the program.
  798.     This routine is used as an ultimate bail-out for serious errors that prohibit
  799.     the continuation of the application. Errors that do not require the termination
  800.     of the application should be handled in a different manner. Error checking and
  801.     reporting has a place even in the simplest application. The error number is used
  802.     to index an 'STR#' resource so that a relevant message can be displayed.
  803.  
  804. ————————————————————————————————————————————————————————————————————————————————————*/
  805.  
  806. #pragma segment Main
  807. void AlertUser()
  808. {
  809.     short        itemHit;
  810.  
  811.     SetCursor(&qd.arrow);
  812.     itemHit = Alert(rUserAlert, nil);
  813.     UnLoadTrafficLightLibrary();
  814. } /* AlertUser */